#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
# 
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-11-28 19:46:36
# *************************************************************

import os
import time
import random
import logging
from logging.handlers import RotatingFileHandler
from multiprocessing.dummy import Pool as ThreadPool

from retrying import retry

log = logging.getLogger("Hello")
log.setLevel(logging.DEBUG)
log_file = os.path.join(os.getenv("HOME"), "logs/test.log")
handler = RotatingFileHandler(log_file, 1024*1024, 10)
handler.setLevel(logging.DEBUG)
log.addHandler(handler)

@retry(stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=5000)
def worker(i):
    print "I'm working on", i
    try:
        raise Exception("test")
    except Exception as e:
        log.exception(e)
        log.info("-"*100)
        raise
    time.sleep(random.uniform(0.5, 2))

def main():
    pool = ThreadPool()
    for i in xrange(20):
        pool.apply_async(worker, (i,))
        print "Create a task --->", i

    pool.close()
    pool.join()

# Script starts from here

if __name__ == "__main__":
    main()
